export const exportExcel = {
  methods: {
    downFile (url, parameter) {
      return window.$axios({
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        },
        url: url,
        data: parameter,
        method: 'post',
        responseType: 'blob'
      })
    },
    // 导出表格数据
    exportXls (url = '', params = {}, xlsName = '') {
      // web端下载
      return this.exportXlsNotDate(url, params, xlsName, true)
    },
    exportXlsNotDate (url = '', params = {}, xlsName = '', isDate) {
      return this.exportFile(url, params, xlsName, '.xlsx', isDate)
    },
    async exportFile (url = '', params = {}, fileName = '', suffix = '', isDate) {
      const res = await this.downFile(url, params)
      let data = res.data || res
      if (!data || data.size === 0) {
        this.$message.warning(this.$t('commonality.excelExportErr'))
        throw new Error(this.$t('commonality.excelExportErr'))
      }
      const blobData = new Blob([data])
      let fileNames = ''
      if (isDate) {
        fileNames = fileName + this.formattedDate(new Date()) + suffix
      } else {
        fileNames = fileName + suffix
      }
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blobData, fileNames)
      } else {
        let url = window.URL.createObjectURL(blobData)
        console.log(url)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileNames)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
      }
    },
    formattedDate (currentDate) {
      const year = currentDate.getFullYear()
      const month = String(currentDate.getMonth() + 1).padStart(2, '0')
      const day = String(currentDate.getDate()).padStart(2, '0')
      return `${year}${month}${day}`
    }
  }
}
